import CharacterSettings from './CharacterSettings.js';
import VoiceSettings from './VoiceSettings.js';
import UserSettings from './UserSettings.js';
import apiService from '../../utils/api.js';

class SettingsPanel {
  constructor(onCharacterSettingsChange, onVoiceSettingsChange, onSelectTab, onUserSettingsChange) {
    this.onSelectTab = onSelectTab;
    this.apiService = apiService;
    this.settings = {
      character1: {},
      character2: {},
      user: {}
    };

    // 初始化设置
    this.characterSettings1 = new CharacterSettings(
      async (settings) => {
        await this.apiService.saveCharacterSettings('character1', settings);
        onCharacterSettingsChange(0, settings);
      }
    );

    this.characterSettings2 = new CharacterSettings(
      async (settings) => {
        await this.apiService.saveCharacterSettings('character2', settings);
        onCharacterSettingsChange(1, settings);
      }
    );

    this.voiceSettings1 = new VoiceSettings(
      async (settings) => {
        await this.apiService.saveCharacterSettings('character1', { voice: settings });
        onVoiceSettingsChange(0, settings);
      }
    );

    this.voiceSettings2 = new VoiceSettings(
      async (settings) => {
        await this.apiService.saveCharacterSettings('character2', { voice: settings });
        onVoiceSettingsChange(1, settings);
      }
    );

    // 初始化用户设置
    this.userSettings = new UserSettings(
      async (settings) => {
        const saveResult = await this.apiService.saveUserSettings(settings);
        if (saveResult && this.container) {
          onUserSettingsChange?.(settings);
        } else {
          console.warn('用户设置保存失败或容器未初始化');
        }
      }
    );

    this.container = document.createElement('div');
    this.currentTab = 0;

    // 加载初始设置
    this.loadInitialSettings();
  }

  async loadInitialSettings() {
    this.settings.character1 = await this.apiService.getCharacterSettings('character1');
    this.settings.character2 = await this.apiService.getCharacterSettings('character2');

    // 更新组件状态
    this.characterSettings1.update(this.settings.character1);
    this.characterSettings2.update(this.settings.character2);
    this.voiceSettings1.update(this.settings.character1.voice || {});
    this.voiceSettings2.update(this.settings.character2.voice || {});
  }

  render() {
    this.container.classList.add('settings-panel-container');

    // 创建选项卡
    const tabContainer = document.createElement('div');
    tabContainer.classList.add('tab-container');

    const tab1 = document.createElement('button');
    tab1.textContent = '角色1设置';
    tab1.classList.add('tab-button', 'active');
    tab1.addEventListener('click', () => {
      this.switchTab(0);
      this.onSelectTab?.(0); // 通知外部当前选中的选项卡
    });

    const tab2 = document.createElement('button');
    tab2.textContent = '角色2设置';
    tab2.classList.add('tab-button');
    tab2.addEventListener('click', () => {
      this.switchTab(1);
      this.onSelectTab?.(1); // 通知外部当前选中的选项卡
    });

    const userTab = document.createElement('button');
    userTab.textContent = '用户设置';
    userTab.classList.add('tab-button');
    userTab.addEventListener('click', () => {
      this.switchTab(2);
      this.onSelectTab?.(2); // 通知外部当前选中的选项卡
    });

    tabContainer.appendChild(tab1);
    tabContainer.appendChild(tab2);
    tabContainer.appendChild(userTab);
    this.container.appendChild(tabContainer);

    // 创建内容区域
    this.contentContainer = document.createElement('div');
    this.contentContainer.classList.add('tab-content');

    // 角色1设置
    this.character1Section = document.createElement('section');
    this.character1Section.classList.add('settings-section');
    this.character1Section.appendChild(this.characterSettings1.render());
    this.character1Section.appendChild(this.voiceSettings1.render());

    // 角色2设置
    this.character2Section = document.createElement('section');
    this.character2Section.classList.add('settings-section');
    this.character2Section.appendChild(this.characterSettings2.render());
    this.character2Section.appendChild(this.voiceSettings2.render());

    // 用户设置
    this.userSection = document.createElement('section');
    this.userSection.classList.add('settings-section');
    this.userSection.appendChild(this.userSettings.render());

    // 初始显示角色1设置
    this.contentContainer.appendChild(this.character1Section);
    this.container.appendChild(this.contentContainer);

    return this.container;
  }

  updateCharacterSettings(characterData) {


    // 如果当前显示的是角色1的选项卡，立即更新UI
    if (this.currentTab === 0) {
      this.characterSettings1.update(characterData);
      this.contentContainer.innerHTML = '';
      this.contentContainer.appendChild(this.character1Section);
    }


    // 如果当前显示的是角色2的选项卡，立即更新UI
    if (this.currentTab === 1) {
      this.characterSettings2.update(characterData);
      this.contentContainer.innerHTML = '';
      this.contentContainer.appendChild(this.character2Section);
    }

  }

  async switchTab(tabIndex) {
    console.log(`[切换选项卡] 当前选项卡: ${this.currentTab}, 新选项卡: ${tabIndex}`);
    if (tabIndex === this.currentTab) {
      console.log('[切换选项卡] 选项卡未改变，跳过切换');
      return;
    }

    // 定义默认设置
    let newSettings = tabIndex === 2 ?
      { name: '', avatar: '' } :
      { name: '', personality: '', style: '', avatar: '', voice: {} };

    try {
      // 保存当前选项卡的设置
      if (this.currentTab === 0) {
        console.log('[切换选项卡] 正在保存角色1设置...');
        const settings1 = {
          ...this.characterSettings1.getCurrentSettings(),
          voice: this.voiceSettings1.getCurrentSettings()
        };
        const saveResult1 = await this.apiService.saveCharacterSettings('character1', settings1);
        console.log(`[切换选项卡] 角色1设置保存结果: ${saveResult1}`);
        if (!saveResult1) {
          console.warn('[切换选项卡] 角色1设置保存失败，继续切换');
        }
      } else if (this.currentTab === 1) {
        console.log('[切换选项卡] 正在保存角色2设置...');
        const settings2 = {
          ...this.characterSettings2.getCurrentSettings(),
          voice: this.voiceSettings2.getCurrentSettings()
        };
        const saveResult2 = await this.apiService.saveCharacterSettings('character2', settings2);
        console.log(`[切换选项卡] 角色2设置保存结果: ${saveResult2}`);
        if (!saveResult2) {
          console.warn('[切换选项卡] 角色2设置保存失败，继续切换');
        }
      }

      // 加载新选项卡的设置
      if (tabIndex === 2) {
        console.log('[切换选项卡] 正在加载用户设置...');
        newSettings = await this.apiService.getUserSettings();
        console.log('[切换选项卡] 用户设置加载完成:', newSettings);
      } else {
        const character = tabIndex === 0 ? 'character1' : 'character2';
        console.log(`[切换选项卡] 正在加载${character}设置...`);
        newSettings = await this.apiService.getCharacterSettings(character);
        console.log(`[切换选项卡] ${character}设置加载完成:`, newSettings);
      }

      // 先更新当前选项卡索引
      this.currentTab = tabIndex;
      console.log(`[切换选项卡] 当前选项卡已更新为: ${this.currentTab}`);

      // 更新选项卡样式
      const tabs = this.container.querySelectorAll('.tab-button');
      tabs.forEach(tab => tab.classList.remove('active'));
      tabs[tabIndex].classList.add('active');

      // 更新内容
      this.contentContainer.innerHTML = '';
      if (tabIndex === 0) {
        this.characterSettings1.update(newSettings);
        this.voiceSettings1.update(newSettings.voice || {});
        this.contentContainer.appendChild(this.character1Section);
      } else if (tabIndex === 1) {
        this.characterSettings2.update(newSettings);
        this.voiceSettings2.update(newSettings.voice || {});
        this.contentContainer.appendChild(this.character2Section);
      } else {
        this.userSettings.update(newSettings);
        this.contentContainer.appendChild(this.userSection);
      }
    } catch (error) {
      console.error('切换选项卡时出错:', error);
      // 即使出错也继续执行，使用默认设置
      newSettings = tabIndex === 2 ?
        { name: '', avatar: '' } :
        { name: '', personality: '', style: '', avatar: '', voice: {} };
    }

    // 更新选项卡样式
    const tabs = this.container.querySelectorAll('.tab-button');
    tabs.forEach(tab => tab.classList.remove('active'));
    tabs[tabIndex].classList.add('active');

    // 更新内容
    this.contentContainer.innerHTML = '';
    if (tabIndex === 0) {
      this.characterSettings1.update(newSettings);
      this.voiceSettings1.update(newSettings.voice || {});
      this.contentContainer.appendChild(this.character1Section);
    } else if (tabIndex === 1) {
      this.characterSettings2.update(newSettings);
      this.voiceSettings2.update(newSettings.voice || {});
      this.contentContainer.appendChild(this.character2Section);
    } else {
      this.userSettings.update(newSettings);
      this.contentContainer.appendChild(this.userSection);
    }

    this.currentTab = tabIndex;
  }
}

export default SettingsPanel;
